package com.attendancesystem.controller;


import com.attendancesystem.model.Course;
import com.attendancesystem.service.CourseService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.jasper.tagplugins.jstl.core.Out;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AddCourseController", value = "/AddCourseController")
public class AddCourseController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse rep) throws ServletException, IOException {
        rep.setContentType("application/json;charset=UTF-8");
        rep.setCharacterEncoding("UTF-8");
        JsonNode rootNode = objectMapper.readTree(request.getReader());
        String courseCode = rootNode.get("courseCode").asText();
        String courseName = rootNode.get("courseName").asText();
        String credit = rootNode.get("credit").asText();
        String teacher = rootNode.get("teacher").asText();
        Course course = new Course();
        course.setCourseCode(courseCode);
        course.setCourseName(courseName);
        course.setCredit(Integer.parseInt(credit));
        course.setTeacherId(teacher);
        CourseService courseService = new CourseService();
        boolean result = courseService.addCourse(course);
        System.out.println("result:"+result);
        if (result){
            Writer writer = rep.getWriter();
            objectMapper.writeValue(writer, Collections.singletonMap("success", true));
            writer.flush();
        }else {
            rep.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }


    }
}
